package com.tianyi.comUser;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.tianyi.comUserInfo.ComUserInfoService;
import com.tianyi.company.CompanyService;
import com.tianyi.dao.entity.comUser.ComUser;
import com.tianyi.dao.entity.comUser.ComUserExample;
import com.tianyi.dao.entity.comUserInfo.ComUserInfo;
import com.tianyi.dao.entity.company.Company;
import com.tianyi.dao.mapper.ComUserMapper;
import com.tianyi.fileUpload.FileUploadService;
import com.tianyi.lib.enums.ComUserStatus;
import com.tianyi.lib.model.WebResult;
import com.tianyi.lib.req.AuditUserReq;
import com.tianyi.lib.req.BaseReq;
import com.tianyi.lib.req.UserAuditInfoReq;

import com.tianyi.lib.req.UserQueryReq;
import com.tianyi.sysUser.SysUserService;
import com.tianyi.util.CommUtils;
import com.tianyi.vo.comUser.ComUserDetailVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * com user service
 *
 * @author cuixuhui
 * @date 2020/05/03
 */
@Service
public class ComUserService {

    private static final Logger logger = LoggerFactory.getLogger(ComUserService.class);

    @Autowired
    private ComUserMapper comUserMapper;
    @Autowired
    private ComUserInfoService comUserInfoService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private FileUploadService fileUploadService;

    public void insertComUser(String openId){

        if (StringUtils.isBlank(openId)){
            logger.info("用户登陆open id为空");
        }
        ComUserExample example = new ComUserExample();
        example.setOrderByClause("id DESC");
        example.createCriteria().andOpenIdEqualTo(openId);
        List<ComUser> comUsers = comUserMapper.selectByExample(example);

        if (CollectionUtils.isNotEmpty(comUsers)){
            return;
        }
        //表示新用户进来
        ComUser comUser = new ComUser();
        comUser.setGmtCreate(new Date());
        comUser.setGmtModified(new Date());
        comUser.setOpenId(openId);
        comUser.setAuditStatus(ComUserStatus.NEW.name());

        comUserMapper.insert(comUser);
    }

    public WebResult<PageInfo<ComUserDetailVO> > queryComUserPage(UserQueryReq req) {

        ComUserExample example = new ComUserExample();
        example.setOrderByClause("id DESC");

        if (StringUtils.isNotBlank(req.getKeyword())){
            ComUserExample.Criteria criteria = example.createCriteria();
            ComUserExample.Criteria or = example.or();

            List<Long> comUserIds = comUserInfoService.queryComUserInfoByKeyword(req.getKeyword());
            if (CollectionUtils.isNotEmpty(comUserIds)){
                criteria.andIdIn(comUserIds);
                or.andIdIn(comUserIds);
            }
            if (CommUtils.isPhoneNum(req.getKeyword())){
                Long phoneNum = Long.valueOf(req.getKeyword());
                criteria.andPhoneEqualTo(phoneNum);
                or.andPhoneEqualTo(phoneNum);
            }
        }

        Page<ComUser> comUserPage = comUserMapper.selectByExample(example, new RowBounds(req.getPageNo(), req.getPageSize()));
        PageInfo<ComUser> comUserPageInfo = comUserPage.toPageInfo();

        PageInfo<ComUserDetailVO> userVOPageInfo = new PageInfo<>();
        BeanUtils.copyProperties(comUserPageInfo, userVOPageInfo);

        List<ComUser> pageInfoList = comUserPageInfo.getList();
        if (CollectionUtils.isEmpty(pageInfoList)){
            return WebResult.ok(userVOPageInfo);
        }

        List<Long> sysUserIds = pageInfoList.stream().map(ComUser::getAuditor).collect(Collectors.toList());

        List<Long> comUserIds = pageInfoList.stream().map(ComUser::getId).collect(Collectors.toList());
        Map<Long, String> userIdNameMap = sysUserService.queryUserNameMapByUserIds(sysUserIds);
        List<Company> companies = companyService.queryByComUserIds(comUserIds);
        Map<Long, Company> companyMap = ListUtils.emptyIfNull(companies).stream()
                .collect(Collectors.toMap(Company::getComUserId, ret -> ret, (oldOne, newOne) -> newOne));

        List<ComUserInfo> comUserInfos = comUserInfoService.queryComUserInfosByComUserIds(comUserIds);
        Map<Long, ComUserInfo> userIdInfoMap = ListUtils.emptyIfNull(comUserInfos).stream()
                .collect(Collectors.toMap(ComUserInfo::getComUserId, ret -> ret, (oldOne, newOne) -> newOne));

        List<ComUserDetailVO> comUserVOS = pageInfoList.stream().map(ret -> {
            ComUserDetailVO vo = new ComUserDetailVO();
            BeanUtils.copyProperties(ret, vo);

            vo.setAuditUserCn(userIdNameMap.get(ret.getAuditor()));
            if (StringUtils.isNotBlank(ret.getAuditStatus())){
                vo.setAuditCn(ComUserStatus.valueOf(ret.getAuditStatus()).getValue());
            }
            Company company = companyMap.get(ret.getId());
            if (Objects.nonNull(company)){
                vo.setCompanyName(company.getComName());
            }
            ComUserInfo comUserInfo = userIdInfoMap.get(ret.getId());
            if (Objects.nonNull(comUserInfo)){
                vo.setJobs(comUserInfo.getJobs());
            }
            vo.setUserInfo(comUserInfo);
            vo.setUserCompany(company);
            return vo;
        }).collect(Collectors.toList());
        userVOPageInfo.setList(comUserVOS);

        return WebResult.ok(userVOPageInfo);
    }

    /**
     * 获取前端用户info
     * @param req
     * @return
     */
    public WebResult<ComUserDetailVO> queryComUserDetailById(BaseReq req) {

        if (Objects.isNull(req.getId()) && StringUtils.isBlank(req.getOpenId())){
            return WebResult.error("用户标识为空");
        }
        ComUser comUser = this.queryComUserByIdOrOpenId(req.getId(), req.getOpenId());
        if (Objects.isNull(comUser)){
            return WebResult.error("用户不存在");
        }

        ComUserInfo comUserInfo = comUserInfoService.queryComUserInfoByParentId(comUser.getId());
        Company comUserCompany = companyService.queryComUserCompanyByParentId(comUser.getId());

        ComUserDetailVO vo = new ComUserDetailVO();
        BeanUtils.copyProperties(comUser, vo);

        Map<Long, String> userIdNameMap = sysUserService.queryUserNameMapByUserIds(Arrays.asList(comUser.getAuditor()));
        if (StringUtils.isNotBlank(vo.getAuditStatus())){
            vo.setAuditCn(ComUserStatus.valueOf(vo.getAuditStatus()).getValue());
        }
        vo.setAuditUserCn(userIdNameMap.get(vo.getAuditor()));
        vo.setUserInfo(comUserInfo);
        vo.setUserCompany(comUserCompany);
        return WebResult.ok(vo);
    }

    /**
     * 根据open id/ dbId获取用户
     * @param userId
     * @param openId
     * @return
     */
    public ComUser queryComUserByIdOrOpenId(Long userId, String openId){

        if (Objects.isNull(userId) && StringUtils.isBlank(openId)){
            return null;
        }

        ComUserExample example = new ComUserExample();
        example.setOrderByClause("id DESC");
        if (Objects.nonNull(userId)){
            example.or().andIdEqualTo(userId);
        }
        if (StringUtils.isNotBlank(openId)){
            example.createCriteria().andOpenIdEqualTo(openId);
        }
        List<ComUser> comUsers = comUserMapper.selectByExample(example);

        if (CollectionUtils.isEmpty(comUsers)){
            return null;
        }
        if (comUsers.size() > 1){
            logger.info("queryComUserByIdOrOpenId user more than one");
        }
        return comUsers.get(0);
    }

    /**
     * 前端用户提交审核信息
     * @param req
     * @return
     */
    public WebResult<String> submitUserAuditInfo(UserAuditInfoReq req) {

        if (StringUtils.isBlank(req.getOpenId())){
            return WebResult.error("小程序id 为空");
        }
        if (Objects.isNull(req.getBuCard()) && StringUtils.isBlank(req.getBuCardPath())){
            return WebResult.error("名片不能为空");
        }

        return updateComUserInfo(req);
    }

    public void updateComUserByAuditInfoReq(UserAuditInfoReq req, ComUser comUser){
        if (Objects.isNull(comUser)){
            return;
        }
        comUser.setGmtModified(new Date());
        comUser.setAuditStatus(ComUserStatus.WAIT_AUDIT.name());
        comUser.setPhone(req.getPhone());
        comUser.setUserName(req.getRealName());
        if (StringUtils.isNotEmpty(req.getRemark())){
            comUser.setRemark(req.getRemark());
        }
        comUserMapper.updateByPrimaryKeySelective(comUser);
    }

    public void updateComUserInfoByAuditInfoReq(UserAuditInfoReq req, ComUserInfo comUserInfo){
        if (Objects.isNull(comUserInfo)){
            return;
        }
        comUserInfo.setGmtModified(new Date());
        comUserInfo.setMail(req.getMail());

        String saveFileName = req.getBuCardPath();
        if (Objects.nonNull(req.getBuCard())){
            //老文件删除
            saveFileName = fileUploadService.uploadPhotoWithThumbnails(req.getBuCard());
            String oldFile = comUserInfo.getBuCardPath();
            fileUploadService.deletePhotoWithThumbnails(oldFile);
        }

        if (StringUtils.isBlank(saveFileName)){
            saveFileName = req.getBuCardPath();
        }

        comUserInfo.setBuCardPath(saveFileName);
        comUserInfo.setIdNum(req.getIdNum());
        comUserInfo.setWechatNum(req.getWechatNum());
        comUserInfo.setRealName(req.getRealName());
        comUserInfo.setJobs(req.getJobs());
        comUserInfo.setIdNum(req.getIdNum());

        comUserInfoService.updateComUserInfoByPrimaryKeySelective(comUserInfo);
    }

    public void updateUserCompanyByAuditInfoReq(UserAuditInfoReq req, Company comUserCompany){
        if (Objects.isNull(comUserCompany)){
            return;
        }
        comUserCompany.setGmtModified(new Date());
        comUserCompany.setComName(req.getCompanyName());
        comUserCompany.setComLocation(req.getCompanyLocation());
        comUserCompany.setComLocationDetail(req.getCompanyLocationDetail());
        companyService.updateUserCompanyByPrimaryKeySelective(comUserCompany);
    }

    /**
     * 审核前端用户信息
     * @param req
     * @return
     */
    public WebResult<String> auditUserInfo(AuditUserReq req) {

        if (Objects.isNull(req.getId())){
            return WebResult.error("id 为空");
        }
        if (Objects.isNull(req.getComUserStatus())){
            return WebResult.error("id 为空");
        }
        ComUser comUser = this.queryComUserByIdOrOpenId(req.getId(), req.getOpenId());
        if (Objects.isNull(comUser)){
            return WebResult.error("用户不存在");
        }

        comUser.setGmtModified(new Date());
        comUser.setAuditor(req.getEmpId());
        comUser.setAuditStatus(req.getComUserStatus().name());
        comUserMapper.updateByPrimaryKeySelective(comUser);
        return WebResult.ok("success");
    }

    /**
     * 上传身份信息返回图片名地址
     * @param req
     * @return
     */
    public WebResult<String> userUploadBuCardPhoto(UserAuditInfoReq req) {
        if (StringUtils.isBlank(req.getOpenId())){
            return WebResult.error("小程序id 为空");
        }

        ComUser comUser = this.queryComUserByIdOrOpenId(req.getId(), req.getOpenId());
        if (Objects.isNull(comUser)){
            return WebResult.error("用户不存在");
        }

        //修改用户详情信息
        ComUserInfo comUserInfo = comUserInfoService.queryComUserInfoByParentId(comUser.getId());
        if (Objects.isNull(comUserInfo)) {
            comUserInfo = new ComUserInfo();
            comUserInfo.setGmtCreate(new Date());
            comUserInfo.setGmtModified(new Date());
            comUserInfo.setComUserId(comUser.getId());
            comUserInfoService.insertComUserInfo(comUserInfo);
        }

        String saveFileName = fileUploadService.uploadPhotoWithThumbnails(req.getBuCard());
        if (StringUtils.isNotBlank(saveFileName)){
            //老文件删除
            String oldFile = comUserInfo.getBuCardPath();
            fileUploadService.deletePhotoWithThumbnails(oldFile);
            comUserInfo.setBuCardPath(saveFileName);
        }
        comUserInfoService.updateComUserInfoByPrimaryKeySelective(comUserInfo);
        return WebResult.ok(saveFileName);
    }

    public WebResult<String> updateComUserInfo(UserAuditInfoReq req) {

        if (Objects.isNull(req.getId())){
            return WebResult.error("id 为空");
        }
        if (Objects.isNull(req.getPhone())){
            return WebResult.error("电话号码为空");
        }
        ComUser comUser = this.queryComUserByIdOrOpenId(req.getId(), req.getOpenId());
        if (Objects.isNull(comUser)){
            return WebResult.error("用户不存在");
        }

        //修改用户信息
        updateComUserByAuditInfoReq(req, comUser);

        //修改用户详情信息
        ComUserInfo comUserInfo = comUserInfoService.queryComUserInfoByParentId(comUser.getId());
        if (Objects.isNull(comUserInfo)) {
            comUserInfo = new ComUserInfo();
            comUserInfo.setGmtCreate(new Date());
            comUserInfo.setGmtModified(new Date());
            comUserInfo.setComUserId(comUser.getId());
            comUserInfoService.insertComUserInfo(comUserInfo);
        }
        updateComUserInfoByAuditInfoReq(req, comUserInfo);

        //修改公司信息
        Company comUserCompany = companyService.queryComUserCompanyByParentId(comUser.getId());
        if (Objects.isNull(comUserCompany)) {
            comUserCompany = new Company();
            comUserCompany.setGmtCreate(new Date());
            comUserCompany.setGmtModified(new Date());
            comUserCompany.setComUserId(comUser.getId());
            companyService.insertUserCompany(comUserCompany);
        }
        updateUserCompanyByAuditInfoReq(req, comUserCompany);

        return WebResult.ok("success");
    }

    /**
     * 删除前台用户
     * @param req
     * @return
     */
    public WebResult<String> deleteComUserById(UserQueryReq req) {

        ComUser comUser = this.queryComUserByIdOrOpenId(req.getId(), req.getOpenId());
        if (Objects.isNull(comUser)){
            return WebResult.error("用户不存在");
        }
        comUserMapper.deleteByPrimaryKey(comUser.getId());
        //删除用户详情信息
        ComUserInfo comUserInfo = comUserInfoService.queryComUserInfoByParentId(comUser.getId());
        if (Objects.nonNull(comUserInfo)){
            String oldFile = comUserInfo.getBuCardPath();
            fileUploadService.deletePhotoWithThumbnails(oldFile);
            comUserInfoService.deleteComUserInfoById(comUserInfo.getId());
        }
        //删除公司信息
        Company comUserCompany = companyService.queryComUserCompanyByParentId(comUser.getId());
        if (Objects.nonNull(comUserCompany)){
            companyService.deleteCompanyById(comUserCompany.getId());
        }
        return WebResult.ok("success");
    }
}
